# coding=utf-8
import paho.mqtt.client as mqtt

from Config import config
from Switch import switch


def start():
    # 初始化mqtt模块
    # ClientId不能重复
    client = mqtt.Client(config.mqtt_client_id)
    client.username_pw_set(config.mqtt_user, config.mqtt_pass)
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(config.mqtt_host, config.mqtt_port, config.mqtt_timeout)
    print(str('订阅的topic:')+config.mqtt_topic)
    # client.loop_start()
    client.loop_forever()


def get_switch_result(msg):
    decode = msg.payload.decode("utf-8")
    result = int(decode)
    if 0 == result:
        return False
    else:
        return True


def get_switch_id(topic):
    subtopic = topic.split('/', 3)
    print(subtopic)
    if len(subtopic) != 4 or subtopic[2] != 'switch':
        raise ValueError("主题格式不符")
    return int(subtopic[3])


def on_connect(client, userdata, flags, rc):
    # 链接成功之后的回调
    print(str('链接的 result code:') + str(rc))
    client.subscribe(config.mqtt_topic)


def on_message(client, userdata, msg):
    # 收到消息之后的回调
    print('topic:' + msg.topic + ',' + 'msg:' + msg.payload.decode("utf-8"))
    try:
        # 获取主题里的 switch_id
        switch_id = get_switch_id(msg.topic)
        switch_result = get_switch_result(msg)

        switch.control(switch_id, switch_result)
    except ValueError as e:
        print(e)
    else:
        pass

